<?php

namespace app\astrologer\controller\v6;

use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\zl8\Zl8UserChatReservationRecord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAuthCode;
use app\common\cachemodel\ZlcrAstrAccount;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Env;
use think\exception\DbException;
use think\response\Json;

class User extends AstrAuth
{
    /**
     * 个人中心
     * @return Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function info()
    {
        $host = Env::get('host.photo');
        $accountInfo = (new ZlcrAstrAccount())->getAstrAccountInfo($this->astrInfo['id'], ['balance']);
        $authStatus = $this->astrInfo['auth_status'];
        $passList = [
            0 => $authStatus['custom_report'],
            1 => $authStatus['question_answer_astr'],
            2 => $authStatus['question_answer_dice'],
            3 => $authStatus['question_answer_tarot'],
        ];

        if ($this->astrInfo['uid'])
        {
            $userInfo = (new \app\common\model\User())->getUserinfo(['id' => $this->astrInfo['uid']]);
        }

        if ($this->isConsultAstro)
        {
            $level = $this->consultAccountInfo['level'];
        }
        $zl8UserChatReservationRecordModel = new Zl8UserChatReservationRecord();
        $teamId = $this->astrInfo['team_id'] ?? 0;
        $astrReservationList = $zl8UserChatReservationRecordModel->getAstrReservationList($this->astrInfo['id']);
        $subNum = 0;
        if ($astrReservationList)
        {
            $astrReservationInfo = $zl8UserChatReservationRecordModel->batchGetInfoByIds(array_keys($astrReservationList));
            $nowDate = date('Ymd');
            $nowHour = date('G');
            $nowHour = !$nowHour ? 24 : $nowHour;
            $nowDate .= $nowHour;
            //从当前时间往后所有的预约记录数量
            foreach ($astrReservationInfo as $item)
            {
                if ($nowDate <= $item['date'] . $item['h_id'] &&
                    in_array($item['status'], [
                        $zl8UserChatReservationRecordModel->statusList['waiting_response'],
                        $zl8UserChatReservationRecordModel->statusList['wait_keep_promise'],
                    ], true))
                {
                    $subNum++;
                }
            }
        }
        return show(config('code.success'), '', [
            'id' => $this->astrInfo['id'],
            'name' => $this->astrInfo['nickname'],
            'avatar' => $this->astrInfo['avatar'] ? $host . $this->astrInfo['avatar'] : '',
            'balance' => $accountInfo['balance'],
            'exam_status' => array_sum($passList) === 1 ? '还有考核未通过' : '全部通过',
            'is_profile_completed' => isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0,
            'pass_list' => $passList,
            'uen' => $userInfo['uen'] ?? '',
            'level' => $level ?? 0,
            'is_team' => $teamId > 0 ? 1 : 0,
            'sub_num' => min($subNum, 99),
        ]);
    }

    /**
     * 检查授权码是否已使用
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function checkAuthCode()
    {
        $isInvite = (new Zlcr3ConsultAuthCode())->getAstrCodeStatus($this->astrInfo['id']);
        $inviteCodeAuthed = 0;
        if ($isInvite)
        {
            $inviteCodeAuthed = 1;//0：没有授权；1：已经授权了；
        }

        $astroConfig = (new AppConfig())->configInfo('astro_app');
        if (isset($astroConfig['examine_join_status']) && $astroConfig['examine_join_status'])
        {
            $examineJoinStatus = 0;
        } else
        {
            $examineJoinStatus = 1;
        }

        return show(config('code.success'), 'Success', [
            'invite_code_authed' => $inviteCodeAuthed,
            'step' => \app\astrologer\controller\User::$statusInfo[$this->astrInfo['check_status']],
            'examine_join_status' => $examineJoinStatus,
        ]);
    }


    /**
     * 使用邀请码
     * @return Json
     * @throws \Exception
     */
    public function useAuthCode()
    {
        $code = input('code/s', '');
        $codeInfo = (new Zlcr3ConsultAuthCode())->getInfoById($code);
        if ($codeInfo['astr_id'] || !$codeInfo['status'] || $codeInfo['expire_time'] < $this->request->time())
        {
            return show(config('code.error'), '授权码不可用');
        }
        (new Zlcr3ConsultAuthCode())->updateData($this->astrInfo['id'], $code, ['astr_id' => $this->astrInfo['id'], 'update_time' => time()]);
        return show(config('code.success'), 'Success');
    }
}
